package services;

import dto.AppGroupDto;
import models.AppGroup;
import play.i18n.Lang;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Gipxy group
 * Date: 3/17/12
 */
public class AppGroupService {

    public static AppGroupDto createDto(AppGroup app) {
        AppGroupDto dto = new AppGroupDto();
        dto.id = app.id;
        dto.code = app.code;
        dto.title = app.title;
        dto.order = app.order;
        dto.brief = app.brief;
        dto.language = app.language;

        dto.photoAsBytes = app.photo;

        return dto;
    }

    //check exits: language + code
    public static boolean isExisted(String code, String language) {
        List<AppGroup> fetch = AppGroup.all(AppGroup.class).filter("code", code).filter("language", language).fetch();
        return fetch.size()>0;
    }

    public static AppGroup merge(AppGroupDto dto) {
        AppGroup merged=null;
        if (dto.id!=null) {
            merged = AppGroup.getByKey(AppGroup.class,dto.id);
        }
        if (merged==null){
            merged = new AppGroup();
        }


        merged.title = dto.title;
        merged.code = dto.code;
        merged.brief = dto.brief;
        merged.order = dto.order;
        System.out.println("LANG="+dto.language);
        merged.language = Lang.get();

        if (dto.photo!=null)
            merged.photo = dto.photo.asBytes();

        merged.save();

        return merged;
    }

    public static Collection<String> getAllAppGroupCodes() {
        Set<String> allCodes = new HashSet<String>();

        List<AppGroup> all = AppGroup.all(AppGroup.class).filter("language", Lang.get()).fetch();
        for (AppGroup t : all) {
            allCodes.add(t.code);
        }

        return allCodes;
    }
}
